//
//  UTConnectorWebViewController.swift
//  UniversalTool
//
//  Created by LGB on 2025/3/8.
//

import UIKit
import WebKit
import AVFoundation

enum ConnectorFunction {
    case none
    case connectorClickFunction
    case connectorRefreshFunction
    case connectorRollFunction
}

class UTConnectorWebViewController: UTBaseViewController {
    
    var model: UTConnectorConvenientLinkModel?
    
    @IBOutlet weak var navigationHeight: NSLayoutConstraint!
    @IBOutlet weak var linkLabel: UILabel!
    @IBOutlet weak var webContentView: UIView!
    lazy var webView: WKWebView = {
        let configuration = WKWebViewConfiguration()
        configuration.allowsInlineMediaPlayback = true
        configuration.allowsAirPlayForMediaPlayback = true
        configuration.allowsPictureInPictureMediaPlayback = true
        configuration.mediaTypesRequiringUserActionForPlayback = []
        configuration.preferences.javaScriptEnabled = true
        configuration.preferences.javaScriptCanOpenWindowsAutomatically = true
        configuration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        let script = """
        window.console.log = (function(originalLog) {
            return function(...args) {
                window.webkit.messageHandlers.consoleLogger.postMessage(args.join(' '));
                originalLog.apply(console, args);
            };
        })(console.log);
        """
        configuration.userContentController.addUserScript(WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false))
        configuration.userContentController.add(self, name: "consoleLogger")
        let webView = WKWebView(frame: .zero, configuration: configuration)
        webView.navigationDelegate = self
        webView.backgroundColor = .white
        webView.scrollView.showsVerticalScrollIndicator = false
        webView.scrollView.contentInsetAdjustmentBehavior = .never
        view.addSubview(webView)
        return webView
    }()
    lazy var movableView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "miaozhun"))
        imageView.isHidden = true
        imageView.isUserInteractionEnabled = true
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
        imageView.addGestureRecognizer(panGesture)
        return imageView
    }()
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipHeight: NSLayoutConstraint!
    @IBOutlet weak var settingView: UIView!
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var pauseButton: UIButton!
    @IBOutlet weak var functionView: UIView!
    
    var functionStyle: ConnectorFunction = .none
    
    lazy var simulateModel: UTSimulateModel = {
        if let data = UTConnectorHelper.connectorInfo() {
            return data.simulateModel
        }
        return UTSimulateModel()
    }()
    var timer: Timer?
    var clickCount = 0
    var audioPlayer: AVAudioPlayer?
    
    /// 连续刷新定时
    var refreshTimer: Timer?
    /// 刷新间隔
    let refreshInterval = 1.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        configData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        stopAllFunction()
    }
    
    fileprivate func setupViews() {
        navigationHeight.constant = UIApplication.shared.statusBarFrame.height + 44
        webContentView.addSubview(webView)
        webView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        webContentView.addSubview(movableView)
        movableView.snp.makeConstraints { make in
            make.right.equalTo(-34.5)
            make.centerY.equalToSuperview()
            make.width.equalTo(45)
            make.height.equalTo(45)
        }
        self.startButton.titleLabel?.adjustsFontSizeToFitWidth = true
    }
    
    fileprivate func configData() {
        if let model = model {
            if let link = model.link, let urlString = link.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
               let url = URL(string: urlString) {
                linkLabel.text = model.link
                webView.load(URLRequest(url: url))
            }
        }
    }
    
    fileprivate func clickFunctionStatusDidChange(_ status: Bool) {
        if status {
            stopAllFunction()
            if functionStyle == .connectorClickFunction {
                movableView.isHidden = false
                tipView.isHidden = false
                tipHeight.constant = 30
            }else {
                movableView.isHidden = true
                tipView.isHidden = true
                tipHeight.constant = 0
            }
            settingView.isHidden = false
            functionView.isHidden = true
        }else {
            functionStyle = .none
            movableView.isHidden = true
            tipView.isHidden = true
            tipHeight.constant = 0
            settingView.isHidden = true
            functionView.isHidden = false
            stopAllFunction()
        }
    }
    
    fileprivate func stopAllFunction() {
        if let timer = timer {
            timer.invalidate()
            self.timer = nil
        }
        audioPlayer = nil
        if let timer = refreshTimer {
            timer.invalidate()
            self.refreshTimer = nil
        }
       
        stopScrollToBottom()
    }
    
    @IBAction func goBack(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
        guard let view = gesture.view, let superview = view.superview else { return }
        let translation = gesture.translation(in: superview)

        // 计算新位置
        var newCenterX = view.center.x + translation.x
        var newCenterY = view.center.y + translation.y

        // 获取父视图的边界
        let minX = view.bounds.width / 2
        let maxX = superview.bounds.width - minX
        let minY = view.bounds.height / 2
        let maxY = superview.bounds.height - minY

        // 限制 view 只能在父视图范围内移动
        newCenterX = min(max(newCenterX, minX), maxX)
        newCenterY = min(max(newCenterY, minY), maxY)

        // 更新视图位置
        view.center = CGPoint(x: newCenterX, y: newCenterY)

        // 重置手势的偏移量
        gesture.setTranslation(.zero, in: superview)
    }

    
    @IBAction func reloadWeb(_ sender: UIButton) {
        self.webView.reload()
    }
    
    @IBAction func webGoBack(_ sender: UIButton) {
        if self.webView.canGoBack {
            self.webView.goBack()
        }
    }
    
    @IBAction func webGoNext(_ sender: UIButton) {
        if self.webView.canGoForward {
            self.webView.goForward()
        }
    }
    
    @IBAction func exit(_ sender: UIButton) {
        self.startButton.isHidden = false
        self.pauseButton.isHidden = true
        clickFunctionStatusDidChange(false)
    }
    
    @IBAction func start(_ sender: UIButton) {
        self.startButton.isHidden = true
        self.pauseButton.isHidden = false
        switch functionStyle {
        case .connectorClickFunction:
            startClickSimulation()
        case .connectorRefreshFunction:
            startAutoRefresh(interval: TimeInterval(simulateModel.refreshFrequency))
        case .connectorRollFunction:
            startScrollToBottom()
        default:
            break
        }
        
    }
    
    @objc func startClickSimulation() {
        clickCount = 0
        let clickInterval = 60.0 / Double(simulateModel.frequency)
        timer = Timer.scheduledTimer(timeInterval: TimeInterval(clickInterval), target: self, selector: #selector(mockClick), userInfo: nil, repeats: true)
    }

    @objc func mockClick() {
        let maxClicks = Int(Double(simulateModel.duration) / (60.0 / Double(simulateModel.frequency)))
        if clickCount >= maxClicks {
            timer?.invalidate()
            timer = nil
            return
        }
        
        clickCount += 1
        if simulateModel.soundStatus {
            playClickSound()
        }
        
        let webViewFrame = webView.convert(movableView.bounds, from: movableView)
        let contentOffset = webView.scrollView.contentOffset

        let jsScript = """
        (function() {
            var x = Math.round(\(webViewFrame.midX) + window.scrollX - \(contentOffset.x));
            var y = Math.round(\(webViewFrame.midY) + window.scrollY - \(contentOffset.y));

            x = Math.min(Math.max(x, 0), document.documentElement.clientWidth - 1);
            y = Math.min(Math.max(y, 0), document.documentElement.clientHeight - 1);

            console.log("修正后的点击坐标:", x, y);

            var elem = document.elementFromPoint(x, y);
            console.log("点击区域的元素:", elem, "标签:", elem.tagName);
            while (elem && !elem.onclick && elem.tagName !== 'BUTTON' && elem.tagName !== 'A') {
                elem = elem.parentElement;
            }

            if (elem) {
                console.log("最终点击的元素:", elem, "标签:", elem.tagName);
                var eventOptions = { bubbles: true, cancelable: true, view: window };
                elem.dispatchEvent(new MouseEvent('mousedown', eventOptions));
                elem.dispatchEvent(new MouseEvent('mouseup', eventOptions));
                elem.dispatchEvent(new MouseEvent('click', eventOptions));
            } else {
                console.log("未找到可点击元素！");
            }
        })();
        """
        webView.evaluateJavaScript(jsScript) { (result, error) in }
    }

    func playClickSound() {
        // 确保音频文件存在于项目中
        guard let url = Bundle.main.url(forResource: "recorder", withExtension: "mp3") else {
            return
        }
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.volume = 1.0 // 设置音量 (0.0 - 1.0)
            audioPlayer?.prepareToPlay()
            audioPlayer?.play()
        } catch {
        }
    }
    
    @IBAction func setting(_ sender: UIButton) {
        switch functionStyle {
        case .connectorClickFunction:
            let vc = UTSimulateClickViewController()
            vc.model = self.simulateModel
            vc.modalPresentationStyle = .overFullScreen
            present(vc, animated: false)
            vc.handler = { [weak self] model in
                if let self = self {
                    self.simulateModel.frequency = model.frequency
                    self.simulateModel.duration = model.duration
                    self.simulateModel.soundStatus = model.soundStatus
                    if let data = UTConnectorHelper.connectorInfo() {
                        data.simulateModel = self.simulateModel
                        UTConnectorHelper.dc_saveTaskCounterInfo(connector: data)
                    }
                }
            }
            break
        case .connectorRefreshFunction:
            let vc = UTSimulateRefreshViewController()
            vc.model = self.simulateModel
            vc.modalPresentationStyle = .overFullScreen
            present(vc, animated: false)
            vc.handler = { [weak self] model in
                if let self = self {
                    self.simulateModel.refreshFrequency = model.refreshFrequency
                    if let data = UTConnectorHelper.connectorInfo() {
                        data.simulateModel = self.simulateModel
                        UTConnectorHelper.dc_saveTaskCounterInfo(connector: data)
                    }
                }
            }
            break
        case .connectorRollFunction:
            let vc = UTSimulateRollViewController()
            vc.model = self.simulateModel
            vc.modalPresentationStyle = .overFullScreen
            present(vc, animated: false)
            vc.handler = { [weak self] model in
                if let self = self {
                    self.simulateModel.rollInterval = model.rollInterval
                    self.simulateModel.rollArea = model.rollArea
                    if let data = UTConnectorHelper.connectorInfo() {
                        data.simulateModel = self.simulateModel
                        UTConnectorHelper.dc_saveTaskCounterInfo(connector: data)
                    }
                }
            }
            break
        default:
            break
        }
    }
    
    @IBAction func clickFunction(_ sender: UIButton) {
        functionStyle = .connectorClickFunction
        clickFunctionStatusDidChange(true)
    }
    
    @IBAction func refreshFunction(_ sender: UIButton) {
        functionStyle = .connectorRefreshFunction
        clickFunctionStatusDidChange(true)
    }
    
    func startAutoRefresh(interval: TimeInterval) {
        refreshTimer?.invalidate()
        refreshTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
            self?.webView.reload()
        }
    }
    
    @IBAction func rollFunction(_ sender: UIButton) {
        functionStyle = .connectorRollFunction
        clickFunctionStatusDidChange(true)
    }
    
    fileprivate func startScrollToBottom() {
        let slowScrollJS = """
        (function() {
            let interval = \(self.simulateModel.rollInterval); // 滚动间隔（秒）
            let scrollPercent = \(self.simulateModel.rollArea * 100); // 每次滚动的区域百分比（0-100）
            let timer; // 计时器变量
            let isScrolling = false; // 是否正在滚动

            function startAutoScroll() {
                if (isScrolling) return; // 防止重复启动
                isScrolling = true;

                timer = setInterval(() => {
                    let scrollHeight = document.documentElement.scrollHeight;
                    let viewportHeight = window.innerHeight;
                    let currentScroll = window.scrollY;

                    // 计算滚动步长（基于总高度的百分比）
                    let scrollStep = (scrollHeight - viewportHeight) * (scrollPercent / 100);

                    // 计算新的滚动位置
                    let newScroll = currentScroll + scrollStep;

                    // 如果即将滚动到底部，则停止
                    if (newScroll + viewportHeight >= scrollHeight) {
                        window.scrollTo(0, scrollHeight - viewportHeight);
                        stopAutoScroll(); // 停止滚动
                        console.log("滚动到底部，自动停止！");
                    } else {
                        window.scrollTo({ top: newScroll, behavior: "smooth" });
                        console.log(`滚动到: ${newScroll}px`);
                    }
                }, interval * 1000);
            }

            function stopAutoScroll() {
                clearInterval(timer);
                isScrolling = false;
                console.log("滚动已手动停止！");
            }

            // **对外暴露全局控制方法**
            window.startAutoScroll = startAutoScroll;
            window.stopAutoScroll = stopAutoScroll;

            // **默认启动滚动**
            startAutoScroll();
        })();
        """
        webView.evaluateJavaScript(slowScrollJS, completionHandler: nil)
    }
    
    fileprivate func stopScrollToBottom() {
        let stopScrollJS = "stopAutoScroll();"
        webView.evaluateJavaScript(stopScrollJS, completionHandler: nil)
    }
    
}

extension UTConnectorWebViewController: WKNavigationDelegate, WKScriptMessageHandler {
    // MARK: - WKNavigationDelegate 方法，控制 JavaScript 启用
    private func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences) async -> WKNavigationActionPolicy {
        preferences.allowsContentJavaScript = true 
        return .allow
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            if message.name == "consoleLogger" {
                if let messageBody = message.body as? String {
                    print("JavaScript console.log: \(messageBody)")
                }
            }
        }
    
}
